﻿using System;
using System.IO;
using XCI.Config;
using XCI.Helper;
using XCI.Sys;
using XCI.Sys.Model;
using XCI.Windows.Extensions;
using XCI.Windows.Forms;
using XCI.Windows.Helper;

namespace XCI.App
{
    public partial class FrmConfigure : FrmBase
    {
        private readonly WinFormSetting setting = ConfigFactory.Default.Get("WinForm", () => new WinFormSetting());

        public FrmConfigure()
        {
            InitializeComponent();
        }

        private void FillPageSizeList()
        {
            var sz = editPageSizeList.Text.Trim().Split(',');
            comboBoxPageSize.Properties.Items.Clear();
            comboBoxPageSize.Properties.Items.BeginUpdate();
            foreach (var item in sz)
            {
                comboBoxPageSize.Properties.Items.Add(item);
            }
            comboBoxPageSize.Properties.Items.EndUpdate();
        }

        private SysWebApi GetWebApi()
        {
            return new SysWebApi(editId.Text.Trim(),
                    editApiUrl.Text.Trim(),
                    TimeSpan.FromMilliseconds(Convert.ToInt32(editApiTimeout.Value)),
                    false);
        }

        private void FrmConfigure_Load(object sender, EventArgs e)
        {
            WinHelper.SetFormData(tabPane1, setting);
            FillPageSizeList();
            if (setting.CloseMainIsExit)
            {
                CheckEdit8.Checked = true;
            }
            else
            {
                CheckEdit7.Checked = true;
            }

            editId.Select();
        }

        private void BtnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(editId.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定应用标识");
                return;
            }
            if (string.IsNullOrEmpty(editApiUrl.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定服务器");
                return;
            }

            WinHelper.GetFormData(tabPane1, setting);
            setting.CloseMainIsExit = CheckEdit8.Checked;
            setting.ShowNotification = CheckEdit7.Checked;
            ConfigFactory.Default.Save();
            MessageBoxHelper.ShowMessage("保存成功");
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void EditFolder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                editFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void BtnUpload_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(editId.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定应用标识");
                return;
            }
            if (string.IsNullOrEmpty(editApiUrl.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定服务器");
                return;
            }

            WinHelper.GetFormData(tabPane1, setting);
            string folderPath = editFolder.Text;
            if (string.IsNullOrEmpty(folderPath) || !Directory.Exists(folderPath))
            {
                MessageBoxHelper.ShowWarn("请指定更新目录");
                return;
            }
            if (!Directory.Exists(folderPath))
            {
                MessageBoxHelper.ShowWarn("更新目录不存在");
                return;
            }

            if (string.IsNullOrEmpty(setting.ApiUrl))
            {
                MessageBoxHelper.ShowWarn("请指定服务器");
                return;
            }

            try
            {
                //SplashHelper.ShowProgressPanel("正在压缩文件夹...");
                SplashHelper.ShowProgressPanel(this);
                this.Enabled = false;

                string zipFilePath = Path.Combine(IOHelper.TempDirectory, $"{StringHelper.Guid()}.zip");
                IOHelper.CreateDirectoryByPath(zipFilePath);
                ZipHelper.CompressDirectory(zipFilePath, folderPath);
                var fileInfo = new FileInfo(zipFilePath);

                //SplashScreenHelper.ShowWait("正在上传文件...");
                //上传文件
                var api = GetWebApi();
                var url = "/api/sys/upgrade/add";
                var result = api.UploadFile<FileModel>(url, "pack.zip", fileInfo.FullName).EnsureSuccess();
                IOHelper.DeleteFile(fileInfo.FullName);
                if (!result.Success)
                {
                    MessageBoxHelper.ShowError(result.Msg);
                }
                else
                {
                    MessageBoxHelper.ShowMessage("软件更新包上传成功");
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex.Message);
            }
            finally
            {
                this.Enabled = true;
                SplashHelper.CloseProgressPanel();
            }
        }

        private void BtnTest_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(editId.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定应用标识");
                return;
            }
            if (string.IsNullOrEmpty(editApiUrl.Text.Trim()))
            {
                MessageBoxHelper.ShowWarn("请指定服务器");
                return;
            }
            WinHelper.GetFormData(tabPane1, setting);

            try
            {
                this.Enabled = false;
                var api = GetWebApi();

                var url = "/api/sys/system/ping";
                var result = api.Post<string>(url).Data;
                if (!string.IsNullOrEmpty(result))
                {
                    MessageBoxHelper.ShowMessage("连接成功");
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError("连接失败" + DebugHelper.GetExceptionAllMessage(ex));
            }
            finally
            {
                this.Enabled = true;
            }
        }

        private void TabPane1_SelectedPageChanged(object sender, DevExpress.XtraBars.Navigation.SelectedPageChangedEventArgs e)
        {
            if (e.Page.Caption.Equals("软件更新"))
            {
                btnOk.Visible = false;
            }
            else
            {
                btnOk.Visible = true;
            }
        }

        private void EditAllowAutoLockMain_CheckedChanged(object sender, EventArgs e)
        {
            editAutoLockInterval.Enabled = editAllowAutoLockMain.Checked;
        }

        private void EditPageSizeList_EditValueChanged(object sender, EventArgs e)
        {
            FillPageSizeList();
        }
    }
}
